#define _CRT_SECURE_NO_WARNINGS 1
#include"Heap.h"

void HeapPrnit(HP* php)
{
	assert(php);
	for (int i = 0; i < php->size; i++)
	{
		printf("%d ", php->a[i]);
	}
	printf("\n");
}
void HeapInit(HP* php)
{
	assert(php);
	php->a = NULL;
	php->capacity = php->size = 0;
}
void HeapDestroy(HP* php)
{
	assert(php);
	free(php->a);
	php->a = NULL;
	php->capacity = php->size = 0;
}

void Swap(HPDataType* x, HPDataType* y)
{
	HPDataType tmp = 0;
	tmp = *x;
	*x = *y;
	*y = tmp;
}
void adup(HPDataType* a,int child )
{
	int parent = (child - 1) / 2;

	while (child > 0)
	{
		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}

}
void HeapPush(HP* php, HPDataType x)
{
	assert(php);
	if (php->capacity == php->size)
	{
		int newcapacity = php->capacity == 0 ? 4 : 2 * php->capacity;
		HPDataType* tmp = (HPDataType*)realloc(php->a, newcapacity * sizeof(HPDataType));
		if (tmp == NULL)
		{
			printf("fail");
			exit(-1);
		}
		php->a = tmp;
		php->capacity = newcapacity;
	}
	php->a[php->size] = x;
	php->size++;

	adup(php->a, php->size - 1);
}

void addown(HPDataType* a, int size,int parent)
{
	int child = 1 + parent * 2;
	while (child < size)
	{
		if (child+1<size && a[child] < a[child+1])
		{

			if (a[child] < a[parent])
			{
				Swap(&a[child ], &a[parent]);
				parent = child;
				child = 2 * child + 1;
			}
			else
			{
				break;
			}
		}
		else
		{
			if (a[child+1] < a[parent])
			{
				Swap(&a[child+1], &a[parent]);
				parent = child;
				child = 2 * child + 1;
			}
			else
			{
				break;
			}
		}

	}

}
void HeapPop(HP* php)
{
	assert(php);
	assert(php->size > 0);

	Swap(&(php->a[0]), &(php->a[php->size - 1]));
	php->size--;

	addown(php->a, php->size, 0);

}
HPDataType HeapTop(HP* php)
{
	assert(php);
	assert(php->size > 0);

	return php->a[0];
}
bool HeapEmpty(HP* php)
{
	assert(php);

	return php->size == 0;
}
int Heapsize(HP* php)
{
	assert(php);

	return php->size;
}

